package com.neouton.crm.cm.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import com.neouton.common.entity.FeeMainVO;
import com.neouton.common.util.AuthUtils;
import com.neouton.common.util.Constants;
import com.neouton.common.util.PageUtil;
import com.neouton.common.util.ResponseAPI;
import com.neouton.crm.approval.entity.ApprovalVO;
import com.neouton.crm.approval.service.impl.ApprovalServiceImpl;
import com.neouton.crm.cm.entity.SalesCostMigrateVO;
import com.neouton.crm.cm.service.CostMigrateService;
import com.neouton.crm.entity.SysUserEntity;
import com.neouton.crm.op.entity.SalesOpportunityVO;
import com.neouton.crm.op.service.SalesOpportunityService;
import com.neouton.crm.pm.entity.SalesProjectManageVO;
import com.neouton.crm.pm.service.ProjectMemberService;
import com.neouton.crm.sales.entity.SalesAuditVO;
import com.neouton.feginClient.ReimburseService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author TheSail
 * @date 2023/01/11 17:15:42
 * @description
 */
@RequestMapping("costmigrate")
@RestController
public class CostMigrateController {
    @Resource
    private ProjectMemberService projectMemberService;
    @Resource
    private CostMigrateService costMigrateService;
    @Resource
    private ApprovalServiceImpl approvalService;
    @Resource
    private ReimburseService reimburseService;

    /**
     * 查询费用记录
     *
     * @param costMigrateVO
     * @return
     */
    @PostMapping("/queryCostInfo/{pageNum}/{pageSize}")
    public ResponseAPI queryCostInfo(@PathVariable(value = "pageNum") Integer pageNum,
                                     @PathVariable(value = "pageSize") Integer pageSize,
                                     @RequestBody SalesCostMigrateVO costMigrateVO,
                                     @RequestHeader("token") String token) {
//        Integer userId = AuthUtils.getUserId();
//        int authId = projectMemberService.queryAuth(userId, Constants.COST_MODEL_NAME);
        List<SysUserEntity> userList = projectMemberService.queryUserList(AuthUtils.getUserId(),"costRecord", token);
        IPage<SalesCostMigrateVO> page = new Page<>(pageNum, pageSize, true);
        PageUtil<SalesCostMigrateVO> list = costMigrateService.queryCostInfo(page, costMigrateVO, userList, token);
        return ResponseAPI.successData(list);
    }

    /**
     * 查询费用记录   待办
     *
     * @param costMigrateVO
     * @return
     */
    @PostMapping("/queryCostInfoToDo/{pageNum}/{pageSize}")
    public ResponseAPI queryCostInfoToDo(@PathVariable(value = "pageNum") Integer pageNum,
                                     @PathVariable(value = "pageSize") Integer pageSize,
                                     @RequestBody SalesCostMigrateVO costMigrateVO,
                                     @RequestHeader("token") String token) {
        ApprovalVO approvalVO = new ApprovalVO();
        approvalVO.setApprovalType(Constants.COSTRECORD_TASK_TYPE);
        List<ApprovalVO> appList = approvalService.queryApprovalByPage(approvalVO);
        if (appList == null || appList.isEmpty()) {
            return ResponseAPI.successData(new PageUtil(new PageDTO()));
        } else {
            ArrayList<Integer> arrayList = new ArrayList<>();
            for (ApprovalVO item : appList) {
                arrayList.add(item.getApprovalId());
            }
            costMigrateVO.setApprovalList(arrayList);
            IPage<SalesCostMigrateVO> page = new Page<>(pageNum, pageSize, true);
            PageUtil<SalesCostMigrateVO> list = costMigrateService.queryCostInfoAudit(page, costMigrateVO, null, token);
            return ResponseAPI.successData(list);
        }
    }

    /**
     * 查询费用记录   已办
     *
     * @param costMigrateVO
     * @return
     */
    @PostMapping("/queryCostInfoDone/{pageNum}/{pageSize}")
    public ResponseAPI queryCostInfoDone(@PathVariable(value = "pageNum") Integer pageNum,
                                         @PathVariable(value = "pageSize") Integer pageSize,
                                         @RequestBody SalesCostMigrateVO costMigrateVO,
                                         @RequestHeader("token") String token) {
        ApprovalVO approvalVO = new ApprovalVO();
        approvalVO.setApprovalType(Constants.COSTRECORD_TASK_TYPE);
        List<ApprovalVO> appList = approvalService.queryApprovalDoneRecordByType(approvalVO);
        if (appList == null || appList.isEmpty()) {
            return ResponseAPI.successData(new PageUtil(new PageDTO()));
        } else {
            ArrayList<Integer> arrayList = new ArrayList<>();
            for (ApprovalVO item : appList) {
                arrayList.add(item.getApprovalId());
            }
            costMigrateVO.setApprovalList(arrayList);
            IPage<SalesCostMigrateVO> page = new Page<>(pageNum, pageSize, true);
            PageUtil<SalesCostMigrateVO> list = costMigrateService.queryCostInfoAudit(page, costMigrateVO, null, token);
            return ResponseAPI.successData(list);
        }
    }

    /**
     * 查询费用记录   记录
     *
     * @param costMigrateVO
     * @return
     */
    @PostMapping("/queryCostInfoRecord/{pageNum}/{pageSize}")
    public ResponseAPI queryCostInfoRecord(@PathVariable(value = "pageNum") Integer pageNum,
                                         @PathVariable(value = "pageSize") Integer pageSize,
                                         @RequestBody SalesCostMigrateVO costMigrateVO,
                                         @RequestHeader("token") String token) {
        ApprovalVO approvalVO = new ApprovalVO();
        approvalVO.setApprovalType(Constants.COSTRECORD_TASK_TYPE);
        List<ApprovalVO> appList = approvalService.queryApprovalRecordByType(approvalVO,token);
        if (appList == null || appList.isEmpty()) {
            return ResponseAPI.successData(new PageUtil(new PageDTO()));
        } else {
            ArrayList<Integer> arrayList = new ArrayList<>();
            for (ApprovalVO item : appList) {
                arrayList.add(item.getApprovalId());
            }
            costMigrateVO.setApprovalList(arrayList);
            IPage<SalesCostMigrateVO> page = new Page<>(pageNum, pageSize, true);
            PageUtil<SalesCostMigrateVO> list = costMigrateService.queryCostInfoAudit(page, costMigrateVO, null, token);
            return ResponseAPI.successData(list);
        }
    }



    /**
     * 根据id查询费用
     *
     * @param costMigrateVO
     * @return
     */
    @PostMapping("/queryCostById/")
    public ResponseAPI queryCostById(@RequestBody SalesCostMigrateVO costMigrateVO) {
        SalesCostMigrateVO result = costMigrateService.queryCostInfoById(costMigrateVO.getCostMigrateId());
        return ResponseAPI.successData(result);
    }

    /**
     * 查询当前机会下费用
     *
     * @param costMigrateVO
     * @return
     */
    @PostMapping("/queryCostByOpId/")
    public ResponseAPI queryCostByOpId(@RequestBody SalesCostMigrateVO costMigrateVO) {
        List<SalesCostMigrateVO> list = costMigrateService.queryCostById(costMigrateVO);
        return ResponseAPI.successData(list);
    }

    /**
     * 查询当前项目下费用
     *
     * @param projectManageId
     * @return
     */
    @PostMapping("/queryCostByPM/{projectManageId}")
    public ResponseAPI queryCostByPM(@PathVariable("projectManageId") Integer projectManageId) {
        List<SalesCostMigrateVO> list = costMigrateService.queryCostByPM(projectManageId);
        return ResponseAPI.successData(list);
    }

    /**
     * 获取全部项目信息
     *
     * @return
     */
    @PostMapping("/queryProjects/")
    public ResponseAPI queryProjects(@RequestBody SalesProjectManageVO projectManageVO, @RequestHeader("token") String token) {
        List<SalesProjectManageVO> projectManages = costMigrateService.queryProjects(projectManageVO, token);
        return ResponseAPI.successData(projectManages);
    }

    /**
     * 根据工作流ID获取费用记录审批信息
     *
     * @param workId
     * @return
     */
    @PostMapping("/queryCostApprovalByWorkId/{workId}")
    public ResponseAPI queryCostApprovalByWorkId(@PathVariable("workId") Integer workId) {
        return ResponseAPI.successData(costMigrateService.queryCostApprovalByWorkId(workId));
    }

    /**
     * 根据工作流ID获取费用迁移审批信息
     *
     * @param workId
     * @return
     */
    @PostMapping("/queryCostAuditByWorkId/{workId}")
    public ResponseAPI queryCostAuditByWorkId(@PathVariable("workId") Integer workId) {
        return ResponseAPI.successData(costMigrateService.queryCostAuditByWorkId(workId));
    }

    /**
     * 根据机会ID获取费用迁移审批信息
     *
     * @param opId
     * @return
     */
    @PostMapping("/queryCostAuditByOpId/{opId}")
    public ResponseAPI queryCostAuditByOpId(@PathVariable("opId") Integer opId) {
        return ResponseAPI.successData(costMigrateService.queryCostAuditByOpId(opId));
    }

    /**
     * 分页查询费用迁移
     * @param pageNum
     * @param pageSize
     * @param auditVO
     * @param token
     * @return
     */
    @PostMapping("/queryCostAudit/{pageNum}/{pageSize}")
    public ResponseAPI queryCostAudit(@PathVariable(value = "pageNum") Integer pageNum,
                                      @PathVariable(value = "pageSize") Integer pageSize,
                                      @RequestBody SalesAuditVO auditVO,
                                      @RequestHeader("token") String token) {
        List<SysUserEntity> userList = projectMemberService.queryUserList(AuthUtils.getUserId(),Constants.OPPORTUNITY_MODEL_NAME, token);
        IPage<SalesAuditVO> page = new Page<>(pageNum, pageSize, true);
        PageUtil<SalesAuditVO> list = costMigrateService.queryCostAudit(page, auditVO, userList, token);
        return ResponseAPI.successData(list);
    }

    /**
     * 分页查询费用迁移     待办
     * @param pageNum
     * @param pageSize
     * @param auditVO
     * @param token
     * @return
     */
    @PostMapping("/queryCostAuditToDo/{pageNum}/{pageSize}")
    public ResponseAPI queryCostAuditToDo(@PathVariable(value = "pageNum") Integer pageNum,
                                            @PathVariable(value = "pageSize") Integer pageSize,
                                            @RequestBody SalesAuditVO auditVO,
                                            @RequestHeader("token") String token) {
        ApprovalVO approvalVO = new ApprovalVO();
        approvalVO.setApprovalType(Constants.COSTMIGRATE_TASK_TYPE);
        List<ApprovalVO> appList = approvalService.queryApprovalByPage(approvalVO);
        if (appList == null || appList.isEmpty()) {
            return ResponseAPI.successData(new PageUtil(new PageDTO()));
        } else {
            ArrayList<Integer> arrayList = new ArrayList<>();
            for (ApprovalVO item : appList) {
                arrayList.add(item.getApprovalId());
            }
            auditVO.setApprovalList(arrayList);
            IPage<SalesAuditVO> page = new Page<>(pageNum, pageSize, true);
            PageUtil<SalesAuditVO> list = costMigrateService.queryCostAuditInfo(page, auditVO, null, token);
            return ResponseAPI.successData(list);
        }
    }

    /**
     * 分页查询费用迁移     已办
     * @param pageNum
     * @param pageSize
     * @param auditVO
     * @param token
     * @return
     */
    @PostMapping("/queryCostAuditDone/{pageNum}/{pageSize}")
    public ResponseAPI queryCostAuditDone(@PathVariable(value = "pageNum") Integer pageNum,
                                          @PathVariable(value = "pageSize") Integer pageSize,
                                          @RequestBody SalesAuditVO auditVO,
                                          @RequestHeader("token") String token) {
        ApprovalVO approvalVO = new ApprovalVO();
        approvalVO.setApprovalType(Constants.COSTMIGRATE_TASK_TYPE);
        List<ApprovalVO> appList = approvalService.queryApprovalDoneRecordByType(approvalVO);
        if (appList == null || appList.isEmpty()) {
            return ResponseAPI.successData(new PageUtil(new PageDTO()));
        } else {
            ArrayList<Integer> arrayList = new ArrayList<>();
            for (ApprovalVO item : appList) {
                arrayList.add(item.getApprovalId());
            }
            auditVO.setApprovalList(arrayList);
            IPage<SalesAuditVO> page = new Page<>(pageNum, pageSize, true);
            PageUtil<SalesAuditVO> list = costMigrateService.queryCostAuditInfo(page, auditVO, null, token);
            return ResponseAPI.successData(list);
        }
    }

    /**
     * 分页查询费用迁移     记录
     * @param pageNum
     * @param pageSize
     * @param auditVO
     * @param token
     * @return
     */
    @PostMapping("/queryCostAuditRecord/{pageNum}/{pageSize}")
    public ResponseAPI queryCostAuditRecord(@PathVariable(value = "pageNum") Integer pageNum,
                                          @PathVariable(value = "pageSize") Integer pageSize,
                                          @RequestBody SalesAuditVO auditVO,
                                          @RequestHeader("token") String token) {
        ApprovalVO approvalVO = new ApprovalVO();
        approvalVO.setApprovalType(Constants.COSTMIGRATE_TASK_TYPE);
        List<ApprovalVO> appList = approvalService.queryApprovalRecordByType(approvalVO,token);
        if (appList == null || appList.isEmpty()) {
            return ResponseAPI.successData(new PageUtil(new PageDTO()));
        } else {
            ArrayList<Integer> arrayList = new ArrayList<>();
            for (ApprovalVO item : appList) {
                arrayList.add(item.getApprovalId());
            }
            auditVO.setApprovalList(arrayList);
            IPage<SalesAuditVO> page = new Page<>(pageNum, pageSize, true);
            PageUtil<SalesAuditVO> list = costMigrateService.queryCostAuditInfo(page, auditVO, null, token);
            return ResponseAPI.successData(list);
        }
    }



    /**
     * 提交费用记录
     *
     * @param costMigrateVO
     * @return
     */
    @PostMapping("/commitCost/")
    public ResponseAPI commitCost(@RequestBody SalesCostMigrateVO costMigrateVO, @RequestHeader("token") String token) {
        //验证机会状态
        Boolean opById = costMigrateService.testOpById(costMigrateVO.getOpportunityId());
        if (opById) {
            return ResponseAPI.successData("操作失败");
        }
        costMigrateService.commitCost(costMigrateVO, token);
        return ResponseAPI.successData(costMigrateVO.getCostMigrateId());
    }

    /**
     * 添加费用记录
     *
     * @param costMigrateVO
     * @return
     */
    @PostMapping("/addCost/")
    public ResponseAPI addCost(@RequestBody SalesCostMigrateVO costMigrateVO, @RequestHeader("token") String token) {
        //验证机会状态
        Boolean opById = costMigrateService.testOpById(costMigrateVO.getOpportunityId());
        if (opById) {
            return ResponseAPI.successData("操作失败");
        }
        costMigrateService.addCost(costMigrateVO);
        return ResponseAPI.successData(costMigrateVO.getCostMigrateId());
    }

    /**
     * 修改费用记录
     *
     * @param costMigrateVO
     * @return
     */
    @PostMapping("/updateCost/")
    public ResponseAPI updateCost(@RequestBody SalesCostMigrateVO costMigrateVO, @RequestHeader("token") String token) {
        //验证机会状态
        Boolean opById = costMigrateService.testOpById(costMigrateVO.getOpportunityId());
        if (opById) {
            return ResponseAPI.successData("操作失败");
        }
        costMigrateService.updateCost(costMigrateVO);
        return ResponseAPI.successData(costMigrateVO.getCostMigrateId());
    }

    /**
     * 费用迁移审核
     *
     * @param auditVO
     * @param token
     * @return
     */
    @PostMapping("/costMigrateAudit/")
    public ResponseAPI costMigrateAudit(@RequestBody SalesAuditVO auditVO, @RequestHeader("token") String token) {
        costMigrateService.costMigrateAudit(auditVO, token);
        return ResponseAPI.successData(auditVO.getSalesAuditId());
    }

    /**
     * 费用记录审批通过
     *
     * @param costMigrateVO
     * @return
     */
    @PostMapping("/approveCostInfo")
    public ResponseAPI approveCostInfo(@RequestHeader("token") String token, @RequestBody SalesCostMigrateVO costMigrateVO) {
        return ResponseAPI.successData(costMigrateService.approveCostInfo(costMigrateVO, token));
    }

    /**
     * 费用记录审批驳回
     *
     * @param costMigrateVO
     * @return
     */
    @PostMapping("/rejectionCostInfo")
    public ResponseAPI rejectionCostInfo(@RequestHeader("token") String token, @RequestBody SalesCostMigrateVO costMigrateVO) {
        return ResponseAPI.successData(costMigrateService.rejectionCostInfo(costMigrateVO, token));
    }

    /**
     * 费用迁移审批通过
     *
     * @param auditVO
     * @return
     */
    @PostMapping("/approveCostMigrate")
    public ResponseAPI approveCostMigrate(@RequestHeader("token") String token, @RequestBody SalesAuditVO auditVO) {
        return ResponseAPI.successData(costMigrateService.approveCostMigrate(auditVO, token));
    }

    /**
     * 费用迁移审批驳回
     *
     * @param auditVO
     * @return
     */
    @PostMapping("/rejectionCostMigrate")
    public ResponseAPI rejectionCostMigrate(@RequestHeader("token") String token, @RequestBody SalesAuditVO auditVO) {
        return ResponseAPI.successData(costMigrateService.rejectionCostMigrate(auditVO, token));
    }

    /**
     * 获取stateCode状态的所有机会
     *
     * @param token
     * @return 所有匹配的机会点集合
     */
    @PostMapping("/queryOpportunityByState")
    public ResponseAPI queryOpportunityByState(@RequestHeader("token") String token, @RequestBody SalesOpportunityVO opportunityVO) {
        List<SalesOpportunityVO> list = costMigrateService.selectAllOpInfo(opportunityVO);
        List<SalesOpportunityVO> opportunityVOS = list.stream().filter(op -> op.getAuditState() != 0 && op.getAuditState() != 1 && op.getOpportunityState() == 1 && op.getMigrateState() == 0).collect(Collectors.toList());
        return ResponseAPI.successData(opportunityVOS);
    }

    /**
     * 获取所有机会
     *
     * @param token
     * @return 所有匹配的机会点集合
     */
    @PostMapping("/queryOpportunityByAll")
    public ResponseAPI queryOpportunityByAll(@RequestHeader("token") String token, @RequestBody SalesOpportunityVO opportunityVO) {
        List<SalesOpportunityVO> list = costMigrateService.selectAllOpInfo(opportunityVO);
        return ResponseAPI.successData(list);
    }

    /**
     * 根据id删除费用记录
     *
     * @param costMigrateId
     * @param token
     * @return
     */
    @DeleteMapping("/deleteCostById/{costMigrateId}")
    public ResponseAPI deleteCostById(@PathVariable("costMigrateId") Integer costMigrateId, @RequestHeader("token") String token) {
        return ResponseAPI.successData(costMigrateService.deleteCostById(costMigrateId));
    }

    /**
     * 根据机会id查询未迁移成功的费用记录
     *
     * vos未迁移0
     * @param opId
     * @return
     */
    @PostMapping("/queryOpFailTest/{opId}")
    public ResponseAPI queryOpFailTest(@PathVariable("opId") Integer opId,
                                     @RequestHeader("token") String token) {
        List<SalesCostMigrateVO> vos = costMigrateService.queryOpFailTest(opId);
        //查询报销数据
//        FeeMainVO feeMainVO = new FeeMainVO();
//        feeMainVO.setChanceId(opId);
//        ResponseAPI<List<FeeMainVO>> listResponseAPI = reimburseService.queryReimburseListByChanceId(feeMainVO, token);
//        List<FeeMainVO> feeMains = listResponseAPI.getResult();
        //查询该机会迁移状态
        int opTest = costMigrateService.queryOpTest(opId);
        boolean result = ( vos != null && vos.size() > 0)  && opTest != 1;
        return ResponseAPI.successData(result);
    }

    /**
     * 根据机会id查询迁移状态
     * @param opId
     * @return
     */
    @PostMapping("/queryOpTest/{opId}")
    public ResponseAPI queryOpTest(@PathVariable("opId") Integer opId) {
        return ResponseAPI.successData(costMigrateService.queryOpTest(opId));
    }

    /**
     * 查询历史费用记录审批信息
     * @param approvalId
     * @return
     */
    @PostMapping("/queryHistoryCostRecordByApprovalId/{approvalId}")
    public ResponseAPI queryHistoryCostRecordByApprovalId(@PathVariable("approvalId") Integer approvalId) {
        return ResponseAPI.successData(costMigrateService.queryHistoryCostRecordByApprovalId(approvalId));
    }
    /**
     * 查询历史费用迁移审批信息
     * @param approvalId
     * @return
     */
    @PostMapping("/queryHistoryCostMigrateByApprovalId/{approvalId}")
    public ResponseAPI queryHistoryCostMigrateByApprovalId(@PathVariable("approvalId") Integer approvalId) {
        return ResponseAPI.successData(costMigrateService.queryHistoryCostMigrateByApprovalId(approvalId));
    }

}
